package hlhj.fhp.supreme.activitys

import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.jzxiang.pickerview.TimePickerDialog
import com.jzxiang.pickerview.data.Type
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import com.zhihu.matisse.Matisse
import com.zhihu.matisse.MimeType
import com.zhihu.matisse.engine.impl.GlideEngine
import com.zhihu.matisse.internal.entity.CaptureStrategy
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.customview.WPopupWindow
import hlhj.fhp.supreme.customview.WheelView
import hlhj.fhp.supreme.javabean.BaseBean
import hlhj.fhp.supreme.javabean.QNBean
import hlhj.fhp.supreme.javabean.QNRespBean
import hlhj.fhp.supreme.javabean.UserInfoBean
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import hlhj.fhp.supreme.utils.SPHelper
import kotlinx.android.synthetic.main.activity_self_info_aty.*
import java.io.File

class SelfInfoAty : BaseAty() {
    private lateinit var userInfo:UserInfoBean.DataBean
    override fun getContentId(): Int = R.layout.activity_self_info_aty
    private val PICK_PHOTO: Int=1
    private var qnToken=""
    override fun initView() {
        userInfo=SPHelper.getUser(this) as UserInfoBean.DataBean
        OkGo.post<QNBean>(Urls.BaseUrl+Urls.QNTOKEN)
                .params("type",0)
                .execute(object :JsonCallBack<QNBean>(this){
                    override fun onSuccess(response: Response<QNBean>?) {
                        val qnBean = response?.body()
                        if (qnBean?.code==1){
                            qnToken=qnBean.data.token
                        }else{
                            MyUtils.toast("获取七牛参数失败")
                        }
                    }
                })
    }

    override fun onResume() {
        super.onResume()
        OkGo.post<UserInfoBean>(Urls.BaseUrl+ Urls.UserInfo)
                .execute(object : JsonCallBack<UserInfoBean>(this){
                    override fun onSuccess(response: Response<UserInfoBean>?) {
                        val bean = response?.body()
                        if (bean?.code==1){
                            SPHelper.saveUser(this@SelfInfoAty,bean.data)
                            userName.text=bean?.data.name
                            when(bean?.data.sex){
                                1->{
                                    userSex.text="男"
                                }
                                else->{
                                    userSex.text="女"
                                }
                            }
                            userBirth.text=MyUtils.timeStampToStrYMD(bean?.data.birthday.toLong())
                            userPhone.text=bean?.data.mobile
                            Glide.with(this@SelfInfoAty).load(bean?.data.avatar).asBitmap().into(userIcon)
                        }
                    }
                })
    }

    override fun initListener() {
//        TODO("使能监听")
        btBirth.setOnClickListener {
            val timerPicker = TimePickerDialog.Builder()
                    .setTitleStringId("出生年月")
                    .setToolBarTextColor(R.color.homeBottomChecked)
                    .setThemeColor(R.color.homeBottomUnChecked)
                    .setType(Type.YEAR_MONTH_DAY)
                    .setMinMillseconds(MyUtils.dateToStampB("1950-01-01 00:00:00").toLong())
                    .setMaxMillseconds(MyUtils.dateToStampB("2010-01-01 00:00:00").toLong())
                    .setCurrentMillseconds(MyUtils.dateToStampB("1990-01-01 00:00:00").toLong())
                    .setCallBack{
                        timePickerView, millseconds ->
                        val ymd = MyUtils.timeStampToStrYMD(millseconds)
                        userBirth.text=ymd
                        OkGo.post<BaseBean>(Urls.BaseUrl+Urls.CHANGEINFO)
                                .params("birthday",ymd)
                                .execute(object :JsonCallBack<BaseBean>(this){
                                    override fun onSuccess(response: Response<BaseBean>?) {
                                        val body = response?.body()
                                        if (body?.code==1){
                                            MyUtils.toast("修改成功")
                                        }
                                    }
                                })
                    }
                    .build()
            timerPicker.show(supportFragmentManager,"birth")
        }
        btSex.setOnClickListener {
            val wha = LayoutInflater.from(this).inflate(R.layout.wheel_view, null)
            val pickera = wha.findViewById<WheelView>(R.id.wheel) as WheelView
            pickera.addData("男")
            pickera.addData("女")
            pickera.setCenterItem(1)
            val popupWindowa = WPopupWindow(wha)
            popupWindowa.showAtLocation(father, Gravity.BOTTOM, 0, 0)
            wha.findViewById<TextView>(R.id.left).setOnClickListener(View.OnClickListener { popupWindowa.dismiss() })
            wha.findViewById<TextView>(R.id.right).setOnClickListener(View.OnClickListener {
                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.CHANGEINFO)
                        .params("sex",when(pickera.centerItem.toString()){
                            "男"->{
                                1
                            }
                            else->{
                                2
                            }
                        })
                        .execute(object :JsonCallBack<BaseBean>(this){
                            override fun onSuccess(response: Response<BaseBean>?) {
                                val bean = response?.body()
                                if (bean?.code==1){
                                    MyUtils.toast("修改成功")
                                }
                            }
                        })
                userSex.setText(pickera.getCenterItem().toString())
                popupWindowa.dismiss()
            })
        }
        btExit.setOnClickListener {
            finish()
        }
        btIcon.setOnClickListener {
            Matisse.from(this@SelfInfoAty)
                    .choose(MimeType.ofImage())
                    .capture(true)
                    .captureStrategy(CaptureStrategy(true,"hlhj.fhp.supreme.fileprovider"))
                    .showSingleMediaType(true)
                    .countable(true)
                    .maxSelectable(1)
                    .spanCount(3)
                    //                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .thumbnailScale(0.85f)
                    .theme(R.style.Matisse_Zhihu)
                    .imageEngine(GlideEngine())
                    .forResult(PICK_PHOTO)
        }
        btHis.setOnClickListener {
            startActivity(Intent(this@SelfInfoAty,SpendHistoryAty::class.java))
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=Activity.RESULT_OK)return
        if (requestCode==PICK_PHOTO){
            val obtainPathResult = Matisse.obtainPathResult(data)
            val path = obtainPathResult[0]
            val manager = UploadManager()
            manager.put(File(path),null,qnToken, UpCompletionHandler { key, info, response ->
                if (info.isOK){
                    Glide.with(this).load(path).asBitmap().into(userIcon)
                    LogUtil.log("七牛响应--${response.getString("hash")}")
                    OkGo.post<BaseBean>(Urls.BaseUrl+Urls.CHANGEINFO)
                    .params("avatar",response.getString("hash"))
                    .execute(object :JsonCallBack<BaseBean>(this){
                        override fun onSuccess(response: Response<BaseBean>?) {
                            val bean = response?.body()
                            if (bean?.code==1){
                                MyUtils.toast("修改成功")
                            }
                        }
                    })
                }else{
                    MyUtils.toast("上传失败")
                }
            },null)

        }
    }
}
